import time

from loguru import logger
from flask import escape, request, jsonify, g, Blueprint

index_view = Blueprint(name='index', import_name=__name__, url_prefix='/')


@index_view.before_request
def authentication():
    """
     前置请求过滤器
    """
    if request.authorization:
        g.user = request.authorization['username']
    else:
        logger.info("匿名用户")
        g.user = 'Anonymous'


@index_view.route('/')
def hello():
    name = request.args.get("name", "World")
    time.sleep(1)
    return f'Hello, {escape(name)}!'


@index_view.route('/json', methods=['GET', 'POST'])
def json():
    """
    返回json格式的数据
    """
    logger.debug('request：[{}]', request)
    logger.debug('request：[{}]', request.environ)
    response = jsonify({'code': 200, 'msg': '返回json数据信息', 'data': g.user})
    logger.debug('response：[{}]', response)
    logger.debug('response：[{}]', response.data)
    return response


@index_view.route("/exception")
def exception_demo():
    """
    错误捕获测试
    """
    raise TypeError("输入错误")
